/* 
 * File:   Button.cpp
 * Author: lgr013
 * 
 * Created on 11 de octubre de 2014, 16:55
 */

#include "Button.h"

//Vector de rectangulos para guardar los sprites
SDL_Rect gSpriteClips[ BUTTON_SPRITE_TOTAL ];
SBSImage* gButtonSpriteSheetTexture = new SBSImage();


Button::Button()
{
	mPosition.x = 0;
	mPosition.y = 0;
	mCurrentSprite = BUTTON_SPRITE_MOUSE_OUT;
}

void Button::setPosition( int x, int y )
{
	mPosition.x = x;
	mPosition.y = y;
}

bool Button::handleEvent( SDL_Event* e )
{
	//If mouse event happened
	if( e->type == SDL_MOUSEMOTION || e->type == SDL_MOUSEBUTTONDOWN || e->type == SDL_MOUSEBUTTONUP )
	{
		//Get mouse position
		int x, y;
		SDL_GetMouseState( &x, &y );

		//Check if mouse is in button
		bool inside = true;

		//Mouse is left of the button
		if( x < mPosition.x )
		{
			inside = false;
		}
		//Mouse is right of the button
		else if( x > mPosition.x + BUTTON_WIDTH )
		{
			inside = false;
		}
		//Mouse above the button
		else if( y < mPosition.y )
		{
			inside = false;
		}
		//Mouse below the button
		else if( y > mPosition.y + BUTTON_HEIGHT )
		{
			inside = false;
		}

		//Mouse is outside button
		if( !inside )
		{
			mCurrentSprite = BUTTON_SPRITE_MOUSE_OUT;
		}
		//Mouse is inside button
		else
		{
			//Set mouse over sprite
			switch( e->type )
			{
				case SDL_MOUSEMOTION:
				mCurrentSprite = BUTTON_SPRITE_MOUSE_OVER_MOTION;
				break;
			
				case SDL_MOUSEBUTTONDOWN:
				mCurrentSprite = BUTTON_SPRITE_MOUSE_DOWN;
                                return true;
			}
		}
	}
        return false;
}
	
bool Button::loadSprite(int swidth, int sheight,SDL_Renderer** gRenderer)
{
	//Loading success flag
	bool success = true;

	//Load sprites
	if( !(gButtonSpriteSheetTexture->loadMedia( "Img/myButton.png", gRenderer)))
	{
//		printf( "Failed to load button sprite texture!\n" );
		success = false;
	}
	else
	{
		//Set sprites
		for( int i = 0; i < BUTTON_SPRITE_TOTAL; ++i )
		{
			gSpriteClips[ i ].x = 0;
			gSpriteClips[ i ].y = i * 71.6666667;
			gSpriteClips[ i ].w = BUTTON_WIDTH;
			gSpriteClips[ i ].h = BUTTON_HEIGHT;
		}

		//Set buttons in corners
		this->setPosition(120, sheight/2+50);
                
	}

	return success;
}

void Button::render(SDL_Renderer** gRenderer)
{
    SDL_Rect renderQuad={mPosition.x, mPosition.y,gButtonSpriteSheetTexture->getWidth(), gButtonSpriteSheetTexture->getHeight()};
    if (gSpriteClips != NULL)
    {
        renderQuad.w = gSpriteClips[mCurrentSprite].w;
        renderQuad.h = gSpriteClips[mCurrentSprite].h;
    }
    SDL_RenderCopyEx(*gRenderer, gButtonSpriteSheetTexture->getTexture(), &gSpriteClips[mCurrentSprite], &renderQuad, 0.0, &this->mPosition, SDL_FLIP_NONE );
}

